#include "../include/udp_broadcast_send.h"

struct send_info
{
    int socket_fd;
    struct sockaddr_in send_addr;
};

void handle(void *arg)
{
    char buf[] = "紧急求救已取消";
	struct send_info si = *(struct send_info *)arg;
    sendto(si.socket_fd, buf, strlen(buf), 0, (struct sockaddr *)&si.send_addr, sizeof(struct sockaddr_in));
}

void* udp_send(void *arg)
{
    struct send_info si;
    bzero(&si, sizeof(struct send_info));

    printf("广播发送端(UDP协议)...............\n");
    
    //1、创建数据报套接字
    int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_fd < 0)
    {
        perror("socket failed");
        exit(1);
    }

    //2、设置套接字文件描述符socketfd的属性为广播（也就是允许发送广播数据包） 
    int on = 1;
    setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
    
    //3、发送数据，并且指定接收方为广播地址
    struct sockaddr_in send_addr;//IPV4地址结构体变量
    send_addr.sin_family = AF_INET;
    send_addr.sin_port = htons(UDP_BROADCAST_PORT);
    send_addr.sin_addr.s_addr = inet_addr(UDP_BROADCAST_IP);//一定是广播地址，广播发送
    //send_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    si.socket_fd = socket_fd;
    si.send_addr = send_addr;
    pthread_cleanup_push(handle, (void *)&si);

    char buf[BUF_SIZE] = "你好，我现在在电梯遇到了紧急情况需要帮助，电梯位于X市X区X路123号阳光小区五号楼3号电梯，请尽快派人来救援！"; 
    while(1) 
    {
        printf("发送紧急广播求救信息: %s\n", buf);
        sendto(socket_fd, buf, strlen(buf), 0, (struct sockaddr *)&send_addr, sizeof(send_addr));
        sleep(2);
    }

    pthread_cleanup_pop(0); 
    close(socket_fd);
}